package com.omesoft.hksnore.loadpage;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

import com.omesoft.hksnore.MainActivity;
import com.omesoft.hksnore.R;
import com.omesoft.hksnore.loadpage.permision.PermissionsActivity;
import com.omesoft.hksnore.loadpage.permision.PermissionsChecker;
import com.omesoft.hksnore.user.LoginActivity;
import com.omesoft.hksnore.util.L;
import com.omesoft.hksnore.util.data.MySharedPreferencesUtil;
import com.omesoft.hksnore.util.myactivity.MyActivity;
import com.omesoft.hksnore.util.titlebar.MyTitlebarUtil;

import butterknife.ButterKnife;


/**
 * 启动页
 *
 * @autor omesoft_lgc
 * <p>
 * create at 2017/2/16 16:10
 */

public class NewLoadingActivity extends MyActivity {
    private Handler handler;

    private static final int REQUEST_CODE = 0; // 请求码


    private PermissionsChecker mPermissionsChecker; // 权限检测器
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.activity_theme_translucent);
        setContentView(R.layout.snore_activity_loading);
        init();

    }


    protected void init() {


        ButterKnife.bind(this);


        mPermissionsChecker = new PermissionsChecker(this);

        handler = new Handler();

        MyTitlebarUtil.showTitleName(activity," ");


    }

    @Override
    protected void onResume() {
        super.onResume();
        L.e("xx", "load onResume");
        // 缺少权限时, 进入权限配置页面
        if (mPermissionsChecker.getPermissions(PermissionsChecker.PERMISSIONS).length > 0) {
            startPermissionsActivity();
        } else {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadMain();
                }
            }, 2000);
        }
    }

    private void loadMain() {
        Intent it = null;
        if (MySharedPreferencesUtil.isLoginIn(context)) {
        it = new Intent(NewLoadingActivity.this, MainActivity.class);
        }else{
            it = new Intent(NewLoadingActivity.this, LoginActivity.class);
        }
        startActivity(it);
        anim = 1;
        loadAnim();
        NewLoadingActivity.this.finish();
    }

    private void startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(this, REQUEST_CODE, PermissionsChecker.PERMISSIONS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 拒绝时, 关闭页面, 缺少主要权限, 无法运行
        L.e("xx", "load onActivityResult");
        if (requestCode == REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
            L.e("xx", "load onActivityResult 1");
            finish();
        } else {
            L.e("xx", "load onActivityResult 2");
            loadMain();
        }
    }


}
